<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters">
                <el-form-item>
                    <el-input style="width:200px;" v-model.trim="filters.title" size="small" placeholder="标题"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-select size="small" clearable style="width:100%;" v-model="filters.type" placeholder="类型">
                        <el-option label="问卷" value="1"></el-option>
                        <el-option label="上传文件" value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item style="float:right;">
                    <el-button type="primary" v-show="exportBtnVisible" class="button_style" size="small" icon="upload2" @click="exportExcels">导出</el-button>
                </el-form-item>
                <el-form-item style="float:right;">
                    <el-button type="primary" v-show="addBtnVisible" class="button_style" size="small" icon="plus" @click="handleAdd">新增</el-button>
                </el-form-item>
                <el-form-item style="float:right;">
                    <el-button type="primary" v-show="queryBtnVisible" class="button_style" size="small" icon="search" v-on:click="getcustoms(true)">查询</el-button>
                </el-form-item>

            </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="clauses" stripe border :height="winHeight-188" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
            <el-table-column prop="questId" align="center" label="问卷名" width="100">
            </el-table-column>
            <el-table-column prop="title" align="center" label="页面标题" min-width="130" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="introductionTitle" align="center" label="介绍标题" min-width="120" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="introduction" align="center" label="介绍内容" min-width="120" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="statementTitle" align="center" label="声明标题" min-width="130" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="statement" align="center" label="声明内容" min-width="130" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="question" align="center" label="问题" min-width="120" show-overflow-tooltip>
            </el-table-column>
            <!-- <el-table-column prop="statementTitle" align="center" label="声明标题" min-width="130" sortable>
            </el-table-column> -->
            <el-table-column label="操作" width="150" fixed='right'>
                <template scope="scope">
                    <el-button v-show="updateBtnVisible" size="small" type="warning" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
                    <!-- <el-button type="danger" v-show="deleteBtnVisible" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button> -->
                </template>
            </el-table-column>
        </el-table>

        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <el-pagination style="float:right" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page" :page-sizes="[10, 20, 40, 80]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </el-col>

        <!--新增界面-->
        <el-dialog title="新增" v-model="addFormVisible" :close-on-click-modal="false">
            <el-form label-width="120px" :model="addForm" :rules="addFormRules" ref="addForm">
                <el-row>
                    <el-col :xs="24" :sm="20" :md="20" :lg="20">
                        <el-form-item label="类型:" prop="type">
                            <el-select v-model="addForm.type" class="otherWidth" placeholder="请选择类型" @change="typeVal(addForm.type)">
                                <el-option label="问卷" value="1"></el-option>
                                <el-option label="文件上传配置" value="2"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :xs="24" :sm="20" :md="20" :lg="20">
                        <el-form-item label="名称:" prop="type">
                            <el-input v-model="addForm.questId" auto-complete="off"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-show="typeVisble">
                    <el-col :xs="24" :sm="20" :md="20" :lg="20">
                        <el-form-item label="页面标题:" prop="title">
                            <el-input v-model="addForm.title" auto-complete="off">
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :xs="24" :sm="20" :md="20" :lg="20">
                        <el-form-item label="介绍标题:" prop="introductionTitle">
                            <el-input v-model="addForm.introductionTitle" auto-complete="off">
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-show="typeVisble">
                    <el-col :xs="24" :sm="20" :md="20" :lg="20">
                        <el-form-item label="声明标题:">
                            <el-input v-model="addForm.statementTitle" auto-complete="off">
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="20" :md="20" :lg="20">
                        <el-form-item label="声明内容:">
                            <el-input autosize type="textarea" v-model="addForm.statement" auto-complete="off">
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- <el-row>
                    <el-col :xs="24" :sm="20" :md="20" :lg="20"> -->
                <el-form-item label="问题:">
                    <!-- <el-input autosize type="textarea" v-model="addForm.question" auto-complete="off">
                            </el-input> -->
                    <div class="kboder" @click="PreviewQuestion('add')" style="height:120px;min-width:160px;width:80%;">
                        <div id="addPreviewQues" class="ksboder"></div>
                    </div>
                    <span style="color:#ff4949;">每个问题用~隔开</span>
                </el-form-item>
                <!-- </el-col>
                </el-row> -->
                <el-row v-show="uploadNumVisble">
                    <el-col :xs="24" :sm="20" :md="10" :lg="10">
                        <el-form-item label="最小上传个数:">
                            <el-input v-model="addForm.limitItem.min" auto-complete="off">
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="20" :md="10" :lg="10">
                        <el-form-item label="最大上传个数:">
                            <el-input v-model="addForm.limitItem.max" auto-complete="off">
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="介绍内容:">
                    <div class="kboder" @click="Preview('add')" style="height:120px;min-width:160px;width:80%;">
                        <div id="addPreview" class="ksboder">
                        </div>
                    </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="addFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
            </div>
        </el-dialog>

        <!-- 修改 -->
        <el-dialog title="修改" v-model="editFormVisible" :close-on-click-modal="false">
            <el-form :model="editForm" label-width="120px" :rules="editFormRules" ref="editForm">
                <el-row>
                    <el-col :xs="24" :sm="20" :md="20" :lg="20">
                        <el-form-item label="类型:" prop="type">
                            <el-select v-model="editForm.type" class="otherWidth" placeholder="是否显示" @change="typeVal(editForm.type)">
                                <el-option label="问卷" value="1"></el-option>
                                <el-option label="文件上传配置" value="2"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :xs="24" :sm="20" :md="20" :lg="20">
                        <el-form-item label="名称:" prop="questId">
                            <el-input v-model="editForm.questId" auto-complete="off"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-show="typeVisble">
                    <el-col :xs="24" :sm="20" :md="20" :lg="20">
                        <el-form-item label="页面标题:" prop="title">
                            <el-input v-model="editForm.title" auto-complete="off">
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :xs="24" :sm="20" :md="20" :lg="20">
                        <el-form-item label="介绍标题:" prop="introductionTitle">
                            <el-input v-model="editForm.introductionTitle" auto-complete="off">
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-show="typeVisble">
                    <el-col :xs="24" :sm="20" :md="20" :lg="20">
                        <el-form-item label="声明标题:">
                            <el-input v-model="editForm.statementTitle" auto-complete="off">
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="20" :md="20" :lg="20">
                        <el-form-item label="声明内容:">
                            <el-input autosize type="textarea" v-model="editForm.statement" auto-complete="off">
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :xs="24" :sm="20" :md="20" :lg="20">
                        <el-form-item label="问题:">
                            <!-- <el-input autosize type="textarea" v-model="editForm.question" auto-complete="off">
                            </el-input> -->
                            <div class="kboder" @click="PreviewQuestion('edit')" style="height:120px;min-width:160px;width:80%;">
                                <div id="editPreviewQues" class="ksboder">
                                </div>
                            </div>
                            <span style="color:#ff4949;">每个问题用~隔开</span>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-show="uploadNumVisble">
                    <el-col :xs="24" :sm="20" :md="10" :lg="10">
                        <el-form-item label="最小上传个数:">
                            <el-input v-model="editForm.limitItem.min" auto-complete="off">
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="20" :md="10" :lg="10">
                        <el-form-item label="最大上传个数:">
                            <el-input v-model="editForm.limitItem.max" auto-complete="off">
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="介绍内容:">
                    <div class="kboder" @click="Preview('edit')" style="height:120px;min-width:160px;width:80%;">
                        <div id="editPreview" class="ksboder">
                        </div>
                    </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="editFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
            </div>
        </el-dialog>

        <el-dialog title="修改" size="large" v-model="editorVisible" :close-on-click-modal="false">
            <!-- <editor ref="myTextEditor" :fileName="'myFile'" :canCrop="canCrop" :uploadUrl="uploadUrl" v-model="content">
            </editor> -->
            <vue-editor v-model="content"></vue-editor>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="editorVisible = false">取消</el-button>
                <el-button type="primary" @click.native="editorSubmit" :loading="editorLoading">确定</el-button>
            </div>
        </el-dialog>

    </section>
</template>

<script>
import util from '../../common/js/util'

import commons from '../../common/js/common'
import { mapState, mapActions } from 'vuex'
import { questionList, addQuestionnaire, removeClause, base, clauseTitleList } from '../../api/api';
import { VueEditor, Quill } from 'vue2-editor';
import editor from '../../components/Quilleditor.vue'
export default {
    components: {
        editor,
        VueEditor,
        Quill
    },
    data() {
        return {
            restaurants: [],
            state4: '',
            timeout: null,
            canCrop: false,
            uploadUrl: base + '/cxb/admin/uploadWeb/upload',
            roles: [],
            content: '',
            filters: {
                title: '',
                type: ''
            },
            commonObj: '',
            exportTotal: 0,
            loading: '',
            clauses: [],
            lists: [],
            total: 0,
            page: 1,
            pageSize: 10,
            listLoading: false,
            editorLoading: false,
            sels: [],//列表选中列
            defaultData: [],
            userid: '',
            addFormVisible: false,//新增界面是否显示
            editFormVisible: false,//修改界面是否显示
            editorVisible: false,//
            editLoading: false,
            addFormRules: {
                kindCode: [
                    { required: true, message: '请输入条款代码', trigger: 'blur' }
                ],
                clauseTitle: [
                    { required: true, message: '请输入条款标题', trigger: 'blur' }
                ]
            },
            editFormRules: {
                kindCode: [
                    { required: true, message: '请输入条款代码', trigger: 'blur' }
                ],
                clauseTitle: [
                    { required: true, message: '请输入条款标题', trigger: 'blur' }
                ]
            },
            //修改界面数据
            editForm: {
                title: '',
                introductionTitle: '',
                introduction: '',
                statementTitle: '',
                statement: '',
                question: '',
                type: '',
                questId: '',
                limitItem: {
                    'min': '',
                    'max': '',
                }
            },
            detailFormVisible: false,//新增界面是否显示
            addLoading: false,
            IsShow: false,
            typeVisble: false,
            uploadNumVisble: false,
            detailFormRules: {
            },
            //新增界面数据
            addForm: {
                title: '',
                introductionTitle: '',
                introduction: '',
                statementTitle: '',
                statement: '',
                question: '',
                type: '',
                questId: '',
                element: '',
                limitItem: {
                    min: '',
                    max: '',
                }
            },

            queryBtnVisible: false,
            addBtnVisible: false,
            exportBtnVisible: false,
            updateBtnVisible: false,
            deleteBtnVisible: false
        }
    },
    computed: mapState([
        'winWidth',
        'winHeight'
    ]),
    methods: {
        formatCreate: function (row, column) {
            return commons.getDaytime(row.createTime, 1, false);
        },
        formatUpdate: function (row, column) {
            return commons.getDaytime(row.updateTime, 1, false);
        },
        initial() {

            clauseTitleList().then((res) => {
                if (res.data.success) {
                    for (var i in res.data.result) {
                        this.restaurants.push({
                            value: res.data.result[i]
                        });
                    }
                }
            }).catch(() => {

            });
        },
        querySearchAsync(queryString, cb) {
            var restaurants = this.restaurants;
            var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;

            clearTimeout(this.timeout);
            this.timeout = setTimeout(() => {
                cb(results);
            }, 1000);
        },
        createStateFilter(queryString) {
            return (state) => {
                return (state.value.indexOf(queryString.toLowerCase()) != -1);
            };
        },
        handleSelect() {

        },
        handleCurrentChange(val) {
            this.page = val;
            this.getcustoms(true);
        },
        handleSizeChange(val) {
            this.pageSize = val;
            this.getcustoms(true);
        },
        // 类型变化后的触发
        typeVal(val) {
            if (val == 1) {
                this.typeVisble = true;
                this.uploadNumVisble = false;
            } else {
                this.typeVisble = false;
                this.uploadNumVisble = true;
            }
        },
        //获取用户列表
        getcustoms(bool) {
            let para = new FormData();
            // para.append("pageSize", bool ? this.pageSize : this.exportTotal);
            // para.append("pageNumber", bool ? this.page : 1);
            para.append("title", this.filters.title);
            para.append("type", this.filters.type);
            this.listLoading = bool;
            if (!bool) {
                this.loading = this.$loading({
                    lock: true,
                    text: '正在导出',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
            }
            questionList(para).then((res) => {
                this.lists = res.data.result;
                this.total = res.data.result.totalElements;
                this.exportTotal = res.data.result.totalElements;
                this.listLoading = false;
                if (!bool) {
                    this.loading.close();
                    this.export2Excel();
                }
                else {
                    this.clauses = res.data.result;
                    this.defaultData = res.data.result;
                }
            });
        },
        //删除
        handleDel: function (index, row) {
            this.$confirm('确认删除该记录吗?', '提示', {
                type: 'warning'
            }).then(() => {
                this.listLoading = true;
                let para = new FormData();
                para.append("id", row.id);
                removeClause(para).then((res) => {
                    this.listLoading = false;
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    });
                    this.getcustoms(true);
                });
            }).catch(() => {

            });
        },

        //table导出excel
        exportExcels: function () {
            this.getcustoms(false);
        },
        export2Excel: function () {
            require.ensure([], () => {
                const { export_json_to_excel } = require('../../vendor/Export2Excel');
                const tHeader = ['序号', '类型', '页面标题', '介绍标题', '介绍内容', '声明标题', '声明内容', '问题'];
                const filterVal = ['id', 'type', 'title', 'introductionTitle', 'introduction', 'statementTitle', 'statement', 'question'];
                const list = this.lists;
                for (var i in list) {
                    list[i].type = list[i].type == 1 ? '问卷' : '文件上传';
                }
                const data = this.formatJson(filterVal, list);
                export_json_to_excel(tHeader, data, '问卷列表');
            })
        },
        formatJson: function (filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => v[j]))
        },

        //显示修改界面
        handleEdit: function (index, row) {
            if (row.type == 1) {
                this.typeVisble = true;
                this.uploadNumVisble = false;
            } else {
                this.uploadNumVisble = true;
                this.typeVisble = false;
            }
            this.editFormVisible = true;
            this.editForm = row;
            setTimeout(function () {
                $('#editPreview').html(row.introduction);
                $('#editPreviewQues').html(row.question);

            }, 100);
            if (!commons.isEmpty(this.editForm.limitItem)) {
                let element = JSON.parse(this.editForm.limitItem);
                this.editForm.limitItem = {
                    min: '0',
                    max: '0'
                };
                this.editForm.limitItem.min = element.min;
                this.editForm.limitItem.max = element.max;
            } else {
                this.editForm.limitItem = {
                    min: '0',
                    max: '0'
                };
            }

        },
        //显示新增界面
        handleAdd: function () {
            this.addFormVisible = true;
            this.state4 = '';
            this.addForm = {
                title: '',
                introductionTitle: '',
                introduction: '',
                statementTitle: '',
                statement: '',
                question: '',
                type: '',
                limitItem: {
                    min: '',
                    max: '',
                }
            };
            $('#addPreview').html('');
            $('#addPreviewQues').html('');
        },
        //新增提交
        addSubmit: function () {
            this.$refs.addForm.validate((valid) => {
                if (this.addForm.limitItem) {
                    this.addForm.limitItem = JSON.stringify(this.addForm.limitItem);
                }
                if (valid) {
                    this.$confirm('确认提交吗？', '提示', {}).then(() => {
                        this.addLoading = true;
                        // let para = this.addForm;
                        let para = Object.assign({}, this.addForm);
                        addQuestionnaire(para).then((res) => {
                            if (res.data.success) {
                                this.$message({
                                    message: '提交成功',
                                    type: 'success'
                                });
                                this.$refs['addForm'].resetFields();
                                this.addFormVisible = false;
                                this.getcustoms(true);
                            }
                            else {
                                this.$message({
                                    message: res.data.result,
                                    type: 'error'
                                });
                            }
                            this.addLoading = false;

                        }).catch(() => {
                            this.addLoading = false;
                        });
                    });
                }
            });
        },
        //修改
        editSubmit: function () {
            this.$refs.editForm.validate((valid) => {
                if (valid) {
                    this.$confirm('确认提交吗？', '提示', {}).then(() => {
                        this.editLoading = true;
                        if (this.editForm.limitItem) {

                            this.editForm.limitItem = JSON.stringify(this.editForm.limitItem);
                        }
                        // let para = this.editForm;
                        let para = Object.assign({}, this.editForm);
                        addQuestionnaire(para).then((res) => {
                            this.editLoading = false;
                            if (res.data.success) {
                                this.$message({
                                    message: '提交成功',
                                    type: 'success'
                                });
                                this.$refs['editForm'].resetFields();
                                this.editFormVisible = false;
                                this.getcustoms(true);
                            }
                            else {
                                this.$message({
                                    message: res.data.result,
                                    type: 'error'
                                });
                                this.$refs['editForm'].resetFields();
                                this.editFormVisible = false;
                                this.getcustoms(true);
                            }

                        }).catch(() => {
                            this.editLoading = false;
                        });;
                    });
                }
            });
        },
        Preview(str) {
            let _this = this;
            _this.editorVisible = true;
            _this.content = '';
            if (str == "add") {
                _this.content = $('#addPreview').html();
                _this.commonObj = 'addPreview';
            }
            else {
                _this.content = $('#editPreview').html();
                _this.commonObj = 'editPreview';
            }
            this.$store.commit('EDITORPICTURE_VALUE', 'clause');
        },

        PreviewQuestion(str) {
            let _this = this;
            _this.editorVisible = true;
            _this.content = '';
            if (str == "add") {
                _this.content = $('#addPreviewQues').html();
                _this.commonObj = 'addPreviewQues';
            }
            else {
                _this.content = $('#editPreviewQues').html();
                _this.commonObj = 'editPreviewQues';
            }
            this.$store.commit('EDITORPICTURE_VALUE', 'clause');
        },
        editorSubmit: function () {
            let _this = this;
            $('#' + _this.commonID).html(_this.content);
            if (_this.commonObj == "addPreview") {
                $('#addPreview').html(_this.content);
                _this.addForm.introduction = _this.content;
            } else if (_this.commonObj == "editPreview") {
                $('#editPreview').html(_this.content);
                _this.editForm.introduction = _this.content;
            } else if (_this.commonObj == "editPreviewQues") {
                $('#editPreviewQues').html(_this.content);
                _this.editForm.question = _this.content;
            } else {
                $('#addPreviewQues').html(_this.content);
                _this.addForm.question = _this.content;
            }
            _this.editorVisible = false;
        },

        selsChange: function (sels) {
            this.sels = sels;
        },
        //批量删除
        batchRemove: function () {
            var ids = this.sels.map(item => item.id).toString();
            this.$confirm('确认删除选中记录吗？', '提示', {
                type: 'warning'
            }).then(() => {
                this.listLoading = true;
                let para = new FormData();
                para.append("ids", ids);
                removeAd(para).then((res) => {
                    this.listLoading = false;
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    });
                    this.getcustoms(true);
                });
            }).catch(() => {

            });
        },

        btnShow: function () {
            let thisData = JSON.parse(sessionStorage.getItem('145'));
            let _this = this;
            $.each(thisData, function (i, j) {
                if (thisData[i] == "clauseQuery") {
                    _this.queryBtnVisible = true;
                }
                if (thisData[i] == "clauseAdd") {
                    _this.addBtnVisible = true;
                }
                if (thisData[i] == "clauseExport") {
                    _this.exportBtnVisible = true;
                }
                if (thisData[i] == "clauseUpdate") {
                    _this.updateBtnVisible = true;
                }
                if (thisData[i] == "clauseRemove") {
                    _this.deleteBtnVisible = true;
                }
            });
        }
    },
    mounted() {
        this.getcustoms(true);
        this.initial();
        this.btnShow();
    }
}

</script>

<style scoped>
.kboder {
  border: 1px solid #bfcbd9;
  overflow-y: scroll;
  overflow-x: hidden;
  cursor: pointer;
}
.ksboder {
  margin: 10px;
  word-wrap: break-word;
}
</style>